#include "glLightMap.h"

#include <stdio.h>

#include "glTexture.h"

glLightMap::glLightMap(void)
{ 
    m_depth = 0;
    m_color = 0;
}

glLightMap::~glLightMap(void)
{
    Release();
}

void glLightMap::Release()
{
    m_fbo.Release();

    glDeleteTextures(1, &m_depth);
    glDeleteTextures(1, &m_color);
}

void glLightMap::Reshape(int width, int height, 
                         GLenum colorFormat /* = GL_RGBA16F */, 
                         GLenum depthFormat /* = GL_DEPTH_COMPONENT24_ARB */)
{
    Release();

    colorDesc.Width  = width;
    colorDesc.Height = height;
    colorDesc.Format = colorFormat;

    colorSampler.AddressS = GL_CLAMP;
    colorSampler.AddressT = GL_CLAMP;
    colorSampler.Filter.Min = GL_LINEAR;
    colorSampler.Filter.Mag = GL_LINEAR;

    depthDesc.Width  = width;
    depthDesc.Height = height;
    depthDesc.Format = depthFormat;

    depthSampler.AddressS = GL_CLAMP;
    depthSampler.AddressT = GL_CLAMP;
    depthSampler.Filter.Min = GL_LINEAR;
    depthSampler.Filter.Mag = GL_LINEAR;
    //depthSampler.ComparisonFunc = GL_COMPARE_R_TO_TEXTURE;

    GL_SUBRESOURCE_DATA colorRes, depthRes;
    colorRes.Format = GL_RGBA;
    depthRes.Format = GL_DEPTH_COMPONENT;

    m_depth = glCreateTexture( &depthDesc, &depthRes, &depthSampler);
    m_color = glCreateTexture( &colorDesc, &colorRes, &colorSampler);

    m_fbo.Create();

    m_fbo.Bind();

    m_fbo.AttachTexture(GL_TEXTURE_2D,m_color,  GL_COLOR_ATTACHMENT0);
    m_fbo.AttachTexture(GL_TEXTURE_2D, m_depth, GL_DEPTH_ATTACHMENT);

    viewport.Height = height;
    viewport.Width = width;

    if ( !m_fbo.IsValid() )
        fprintf(stderr, "Error creating offscreen buffer\n");

    m_fbo.Disable();
}

void glLightMap::glBegin()
{
    m_fbo.Bind();

    m_fbo.AttachTexture(GL_TEXTURE_2D, m_color, GL_COLOR_ATTACHMENT0);
    m_fbo.AttachTexture(GL_TEXTURE_2D, m_depth, GL_DEPTH_ATTACHMENT);
    
    glSetViewport( &viewport );
}

void glLightMap::glEnd()
{
    m_fbo.Disable();
}